package com.mes.handler;

import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.hibernate.Query;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.service.OBDal;
import com.mes.quality.data.EmesqQualityOrderTable;

public class EmesQualityOrderTableHandler extends BaseActionHandler{

	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> map, String jsonStr) {
		JSONObject responseResult = new JSONObject();
		try {
			responseResult.put("result", false);
			responseResult.put("msg", "接口调用失败");
			JSONObject json = new JSONObject(jsonStr);
			if(json.has("tag")){
				if(json.getInt("tag") == 1){//审核
					responseResult = this.Audite(json);	
				}else{
					responseResult.put("result", false);
					responseResult.put("msg", "接口调用失败");
				}
			}
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			try {
				responseResult.put("result", false);
				responseResult.put("msg", "审核失败");
			} catch (JSONException e1) {
			}
			logger.error(e);
		}
		return responseResult;
	}
	
	//审核
	private JSONObject Audite(JSONObject data) throws JSONException {
		JSONObject responseResult = new JSONObject();
		EmesqQualityOrderTable ot = OBDal.getInstance().get(EmesqQualityOrderTable.class, data.getString("id"));
		if("3".equals(ot.getStatus()) || "2".equals(ot.getStatus())){//检出或者不合格
	        String hql = " update from Emesq_Quality_OT ot set status = '4' where ot.id = ? and status in('2','3')";

	        Query query = OBDal.getInstance().getSession().createQuery(hql);
	        query.setParameter(0, ot.getId());
	        int status = query.executeUpdate();
	        if(status > 0 ){
				responseResult.put("result", true);
				responseResult.put("msg", "审核成功");
	        }else{
	        	responseResult.put("result", false);
				responseResult.put("msg", "审核失败");
				return responseResult;
	        }
		}else if("4".equals(ot.getStatus())){
			responseResult.put("result", false);
			responseResult.put("msg", "已审核通过");
			return responseResult;
		}else{
			responseResult.put("result", false);
			responseResult.put("msg", "当前状态不允许审核");
			return responseResult;
		}
		return responseResult;
	}
}